﻿using FastBuild.TimeJob;
using FastBuild;
using DeleteLog.SettingModel;

namespace DeleteLog.Jobs
{
    [Injection(DIPattern = DIPattern.Scoped, IServeice = typeof(DeleteLogJob))]
    [SkipWhileExecuting, ExecuteNow]
    public class DeleteLogJob : IJob
    {
        [Autowired]
        private ILog _logger;

        [Autowired]
        private DeleteLogSetting _setting;

        public async Task Execute()
        {
            try
            {
                if (_setting.Items is null)
                    return;

                _logger.Debug("DeleteLogJob Begin", "DeleteLogJob");

                foreach (var item in _setting.Items)
                {
                    if (!Directory.Exists(item.BasePath))
                        continue;

                    foreach (var tag in item.Tags)
                    {
                        string path = Path.Combine(item.BasePath, tag);

                        if (!Directory.Exists(path))
                            continue;

                        var allLogs = Directory.GetDirectories(path, "*");

                        if (allLogs is null || allLogs.Length <= 0)
                            continue;

                        //排序 如果不超过 KeepDay 就不处理
                        allLogs = allLogs.OrderBy(s => s).ToArray();
                        if (allLogs.Length <= item.KeepDay) continue;

                        //取出总数-KeepDay个进行删除
                        allLogs.Take(allLogs.Length - item.KeepDay).ToList()
                            .ForEach(deletePath =>
                            {
                                _logger.Debug($"删除成功，删除路径为：{deletePath}", "DeleteLogJob");
                                Directory.Delete(deletePath, true);
                            });
                    }
                }

                await Task.CompletedTask;

                _logger.Debug("DeleteLogJob End", "DeleteLogJob");

                GC.Collect();
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "DeleteLogJob Error", "DeleteLogJob");
            }
        }
    }
}
